package com.filex.ads.banner;

import android.content.Context;
import android.support.annotation.NonNull;
import android.webkit.WebView;
import android.webkit.WebViewClient;


import com.filex.ads.common.UrlAction;
import com.filex.ads.common.UrlHandler;

import java.util.EnumSet;

class HtmlWebViewClient extends WebViewClient {

    private final EnumSet<UrlAction> SUPPORTED_URL_ACTIONS = EnumSet.of(
            UrlAction.HANDLE_PHONE_SCHEME,
            UrlAction.OPEN_APP_MARKET,
            UrlAction.OPEN_NATIVE_BROWSER);

    private final Context mContext;
    private final HtmlWebViewListener mHtmlWebViewListener;

    HtmlWebViewClient(HtmlWebViewListener htmlWebViewListener, FilexWebView htmlWebView) {
        mHtmlWebViewListener = htmlWebViewListener;
        mContext = htmlWebView.getContext();
    }

    @Override
    public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
        new UrlHandler.Builder()
                .withSupportedUrlActions(SUPPORTED_URL_ACTIONS)
                .withResultActions(new UrlHandler.ResultActions() {
                    @Override
                    public void urlHandlingSucceeded(@NonNull String url,
                            @NonNull UrlAction urlAction) {
                            mHtmlWebViewListener.onClicked();
                    }

                    @Override
                    public void urlHandlingFailed(@NonNull String url,
                            @NonNull UrlAction lastFailedUrlAction) {
                    }
                })
                .build().handleUrl(mContext, url, true);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        if (mHtmlWebViewListener != null) {
            mHtmlWebViewListener.onLoaded();
        }
    }
}
